﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CommonUtils.Extend
{
    public static class ExEnum
    {
        /// <summary>
        /// 获取枚举的描述值
        /// </summary>
        /// <param name="enum"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum @enum)
        {
            string value = @enum.ToString();
            FieldInfo field = @enum.GetType().GetField(value);
            // 获取描述特性，禁止继承的特性
            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);

            // 当描述特性没有时，直接返回名称
            if (objs.Length == 0)
                return value;

            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];

            return descriptionAttribute.Description;
        }

        /// <summary>
        /// 通过描述获取枚举值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="description"></param>
        /// <returns></returns>
        /// <exception cref="DllNotFoundException"></exception>
        public static T GetEnumByDescription<T>(this string description) where T : Enum
        {
            FieldInfo[] fields = typeof(T).GetFields();

            foreach (var field in fields)
            {
                object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (objs.Length > 0 && objs[0] is DescriptionAttribute da && da.Description == description)
                {
                    return (T)field.GetValue(null);
                }
            }

            throw new DllNotFoundException($"not found {description}");
        }
    }
}
